package com.stylefeng.guns.modular.biz.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.stylefeng.guns.common.constant.factory.PageFactory;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.common.exception.BussinessException;
import com.stylefeng.guns.common.persistence.dao.OrderInfoMapper;
import com.stylefeng.guns.common.persistence.dao.OrderItemMapper;
import com.stylefeng.guns.common.persistence.dao.ProductInfoMapper;
import com.stylefeng.guns.common.persistence.dao.WorkNoticeMapper;
import com.stylefeng.guns.common.persistence.model.*;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.core.util.excel.ExportExcel;
import com.stylefeng.guns.core.util.excel.ImportExcel;
import com.stylefeng.guns.modular.biz.dao.OrderDao;
import com.stylefeng.guns.modular.biz.warpper.OrderInfoWarpper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 订单信息控制器
 * @author fengshuonan
 * @Date 2017-10-17 21:13:36
 */
@Controller
@RequestMapping("/userInfo")
public class UserInfoController extends BaseController {

    private String PREFIX = "/biz/userInfo/";

    @Resource
    private OrderDao orderDao;

    @Resource
    private OrderInfoMapper orderInfoMapper;

    @Resource
    private OrderItemMapper  orderItemMapper;

    @Resource
    ProductInfoMapper productInfoMapper;

    @Resource
    private WorkNoticeMapper workNoticeMapper;

    /**
     * 跳转到订单信息首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "userInfo.html";
    }

    /**
     * 跳转到添加订单信息
     */
    @RequestMapping("/userInfo_add")
    public String userInfoAdd() {
        return PREFIX + "userInfo_add.html";
    }



    /**
     * 跳转到修改订单信息
     */
    @RequestMapping("/userInfo_update/{orderId}")
    public String userInfoUpdate(@PathVariable Integer orderId, Model model) {
        if (ToolUtil.isEmpty(orderId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        OrderInfo  orderInfo=this.orderInfoMapper.selectById(orderId);
        model.addAttribute("order",orderInfo);
        List<OrderItem> list=orderItemMapper.selectList(new EntityWrapper<OrderItem>().eq("order_no", orderInfo.getOrderNo()));
        model.addAttribute("orderItems",list);
        LogObjectHolder.me().set(orderInfo);
        return PREFIX + "userInfo_edit.html";
    }


    @RequestMapping("/order_update/{orderId}")
    public String orderUpdate(@PathVariable Integer orderId, Model model) {
        if (ToolUtil.isEmpty(orderId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        OrderInfo  orderInfo=this.orderInfoMapper.selectById(orderId);
        model.addAttribute("order",orderInfo);
        List<OrderItem> list=orderItemMapper.selectList(new EntityWrapper<OrderItem>().eq("order_no", orderInfo.getOrderNo()));
        model.addAttribute("orderItems",list);
        LogObjectHolder.me().set(orderInfo);
        return PREFIX + "userInfoOrder_edit.html";
    }


    /**
     * 获取订单信息列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(OrderInfo orderInfo) {

        Page<OrderInfo> page = new PageFactory<OrderInfo>().defaultPage();
        Integer deptid= ShiroKit.getUser().getDeptId();//获取当前用户部门id
        if(ShiroKit.getUser().getDeptId()==27){//超级管理员
            deptid=null;
        }
        System.out.println("status"+orderInfo.getStatus());
        List<Map<String, Object>> result = orderDao.getUserInfos(page ,deptid,orderInfo.getOrderNo(), orderInfo.getUserName() ,
                orderInfo.getUserPhone(),orderInfo.getAddress(),orderInfo.getSetupName(),orderInfo.getSetupName(),
                page.getOrderByField(), page.isAsc());
        page.setRecords((List< OrderInfo>) new OrderInfoWarpper(result).warp());
        return super.packForBT(page);
    }


    /**
     * 删除订单信息
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete() {
        return SUCCESS_TIP;
    }


    /**
     * 删除订单item信息
     */
    @RequestMapping(value = "/deleteItem")
    @ResponseBody
    public Object deleteItem(Integer itemId) {
        orderItemMapper.deleteById(itemId);
        return SUCCESS_TIP;
    }


    /**
     * 修改订单信息
     */
    @RequestMapping(value = "/updateUserInfo")
    @ResponseBody
    public Object updateUserInfo(OrderInfo orderInfo,String content){
        orderInfoMapper.updateById(orderInfo);
        return super.SUCCESS_TIP;
    }


    /**
     * 修改订单信息
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(OrderInfo orderInfo,String orderInfosValues) {
        if(orderInfo.getIsYumai()==2){//无需预埋
            orderInfo.setStatus(2);//待装机
        }else if (orderInfo.getIsYumai()==1){
            orderInfo.setStatus(1);//待预埋
        }
        Integer deptid= ShiroKit.getUser().getDeptId();//获取当前用户部门id
        if(orderInfosValues!=null  &&  !"".equals(orderInfosValues)){
            String [] infos=orderInfosValues.split(",");
            System.out.println("length"+infos.length);
            OrderItem orderItem=null;
            String [] item;
            ProductInfo productInfo;
            for(int i=0;i<infos.length; i++){
                item=infos[i].split("-");
                if( "0".equals(item[4]) ){
                    orderItem=new OrderItem();
                    orderItem.setPid(Integer.parseInt(item[2]));
                    orderItem.setOrderNo(orderInfo.getOrderNo());
                    orderItem.setProductType(Integer.parseInt(item[0]));
                    orderItem.setProductTypeName(item[1]);
                    productInfo=productInfoMapper.selectById(Integer.parseInt(item[2]));
                    orderItem.setProductModel(productInfo.getProductModel());
                    orderItem.setQuantity(Integer.parseInt(item[3]));
                    orderItemMapper.insert(orderItem);
                }else {
                    orderItem=new OrderItem();
                    orderItem.setId(Integer.parseInt(item[4]));
                    orderItem.setProductType(Integer.parseInt(item[0]));
                    orderItem.setProductTypeName(item[1]);
                    orderItem.setPid(Integer.parseInt(item[2]));
                    productInfo=productInfoMapper.selectById(Integer.parseInt(item[2]));
                    orderItem.setProductModel(productInfo.getProductModel());
                    orderItem.setQuantity(Integer.parseInt(item[3]));
                    orderItemMapper.updateById(orderItem);
                }
            }
        }
        WorkNotice workNotice=null;
        if(orderInfo.getIsYumai()==1){//需要预埋
            workNotice=new WorkNotice();
            workNotice.setWorkType(1);//预埋管道
            workNotice.setUserName(orderInfo.getUserName());
            workNotice.setUserPhone(orderInfo.getUserPhone());
            workNotice.setAddress(orderInfo.getAddress());
            workNotice.setDealTime(orderInfo.getYumaiTime());
            workNotice.setCreateTime(new Date());
            workNotice.setOrderNo(orderInfo.getOrderNo());
            workNotice.setDeptid(deptid);
            workNoticeMapper.insert(workNotice);//插入预埋工单
        }
        workNotice=new WorkNotice();
        workNotice.setWorkType(2);//安装
        workNotice.setUserName(orderInfo.getUserName());
        workNotice.setUserPhone(orderInfo.getUserPhone());
        workNotice.setAddress(orderInfo.getAddress());
        workNotice.setDealTime(orderInfo.getSetupTime());
        workNotice.setCreateTime(new Date());
        workNotice.setOrderNo(orderInfo.getOrderNo());
        workNotice.setDeptid(deptid);
        workNoticeMapper.insert(workNotice);//出入安装工单
        orderInfoMapper.updateById(orderInfo);
        return super.SUCCESS_TIP;
    }


    /**
     * 新增订单信息
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(OrderInfo orderInfo) {
        orderInfo.setOrderNo(makeTransId());
        orderInfo.setCreateTime(new Date());
        orderInfo.setStatus(0);
        Integer deptid= ShiroKit.getUser().getDeptId();//获取当前用户部门id
        System.out.println("orderInfo"+orderInfo.getRemarks());
        orderInfo.setDeptid(deptid);
        orderInfo.insert();
        return super.SUCCESS_TIP;
    }




    /**
     * 订单信息详情
     */
    @RequestMapping(value = "/detail")
    @ResponseBody
    public Object detail() {
        return null;
    }

    /**
     * 导入
     * @param file
     * @param num
     * @return
     */
    @RequestMapping(value = "/import", method= RequestMethod.POST)
    @ResponseBody
    public Object importFile(@RequestParam("file") MultipartFile file,String num) {
        System.out.println("num"+num+"name"+file.getOriginalFilename());
            Integer deptid= ShiroKit.getUser().getDeptId();//获取当前用户部门id
            try {
                int successNum = 0;
                int failureNum = 0;
                StringBuilder failureMsg = new StringBuilder();
                ImportExcel ei = new ImportExcel(file, 1, 0);
                List<OrderInfo> list = ei.getDataList(OrderInfo.class);
                for (OrderInfo orderInfo : list){
                    try{
                        orderInfo.setOrderNo(makeTransId());
                        orderInfo.setDeptid(deptid);//部门Id
                        orderInfo.setCreateTime(new Date());
                        orderInfo.setStatus(0);
                        orderInfoMapper.insert(orderInfo);
                        successNum++;
                    }catch(ConstraintViolationException ex){
                        failureNum++;
                    }catch (Exception ex) {
                        failureNum++;
                    }
                }
                if (failureNum>0){
                    failureMsg.insert(0, "，失败 "+failureNum+" 条会员积分记录记录。");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        return super.SUCCESS_TIP;
    }

    @RequestMapping(value = "/import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "客户信息数据导入模板.xlsx";
            List<CustomerInfo> list = Lists.newArrayList();
            new ExportExcel("客户信息记录数据", CustomerInfo.class, 1).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            e.getMessage();
        }
        return "redirect:"+"/userInfo/list/";
    }


    public static String makeTransId(){
        Date currTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
        String TradeDate = formatter.format(currTime); // 订单日期
        String b= (Math.abs(new Random().nextLong()) % 10000)+"";
        int lastLen=5-b.length();
        System.err.println("makeTransId:"+b);
        for (int i = 0; i < lastLen; i++) {
            Random rd = new Random();//产生随机数
            b+=rd.nextInt(10);
        }
        String transId = TradeDate+b;
        return transId;
    }
}
